//
//  DAnalysisDatePreferenceViewController.swift
//  Drop
//
//  Created by hushaohua on 2018/2/11.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit

class DAnalysisDatePreferenceViewController: DMoreListViewController {
    
    init() {
        self.analysis = DAnalysisDatePreference();
        super.init(nibName: nil, bundle: nil);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configAnalysis();
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 84, 0);
        self.configNavigationItem();
    }
    
    func configAnalysis() -> Void{
//        self.analysis = DPreferences.defaultPreferences().analysis.copy();
        if (self.analysis.intervalValue.subType == .Custom){
            self.customSection.first!.detail = self.analysis.intervalValue.customDateString;
        }
        self.replaceSection1();
        self.tableView.reloadData();
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func configNavigationItem() -> Void{
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.doneButton());
    }
    
    func doneButton() -> UIButton{
        let button = UIButton(frame: CGRect(x:0,y:0,width:44,height:44));
        button.contentHorizontalAlignment = .right;
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .light);
        button.setTitle("确定", for: .normal);
        button.setTitleColor(UIColor.darkGray, for: .normal);
        button.addTarget(self, action: #selector(doneAction), for: .touchUpInside);
        return button;
    }
    
    var doneClosure: ((DAnalysisDatePreference) -> Void)?;
    @objc func doneAction() -> Void{
        if (self.doneClosure != nil){
            self.doneClosure!(self.analysis);
        }
    }
    
    override func tableRowSections() -> [[DTableRowItem]] {
        var sections = [[DTableRowItem]]();
        sections.append(self.intervalSection);
        sections.append(self.daySection);
        sections.append(self.customSection);
        sections.append(self.allSection);
        return sections;
    }
    
    lazy var intervalSection:[DTableRowItem] = {
        var sections = [DTableRowItem]();
        let day = DTableRowItem(title: "按天", closure: nil);
        sections.append(day);
        sections.append(DTableRowItem(title: "按周", closure: nil));
        sections.append(DTableRowItem(title: "按月", closure: nil));
        return sections;
    }();
    lazy var daySection:[DTableRowItem] = {
        var sections = [DTableRowItem]();
        sections.append(DTableRowItem(title: "今天", closure: nil));
        sections.append(DTableRowItem(title: "最近2天", closure: nil));
        sections.append(DTableRowItem(title: "最近3天", closure: nil));
        sections.append(DTableRowItem(title: "最近4天", closure: nil));
        sections.append(DTableRowItem(title: "最近5天", closure: nil));
        sections.append(DTableRowItem(title: "最近6天", closure: nil));
        return sections;
    }();
    lazy var weekSection : [DTableRowItem] = {
        var sections = [DTableRowItem]();
        sections.append(DTableRowItem(title: "本周", closure: nil));
        sections.append(DTableRowItem(title: "最近2周", closure: nil));
        sections.append(DTableRowItem(title: "最近3周", closure: nil));
        return sections;
    }();
    lazy var monthSection : [DTableRowItem] = {
        var sections = [DTableRowItem]();
        sections.append(DTableRowItem(title: "本月", closure: nil));
        sections.append(DTableRowItem(title: "最近2月", closure: nil));
        sections.append(DTableRowItem(title: "最近3月", closure: nil));
        return sections;
    }();
    lazy var allSection : [DTableRowItem] = {
        var sections = [DTableRowItem]();
        sections.append(DTableRowItem(title: "所有", closure: nil));
        return sections;
    }();
    
    lazy var customSection : [DTableRowItem] = {
        var sections = [DTableRowItem]();
        sections.append(DTableRowItem(title: "自定义 ...", closure: nil));
        return sections;
    }();
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath.section == 1 && self.customController.isEditing){
            return 240;
        }else if (indexPath.section == 2 && self.customController.isEditing){
            return 64;
        }else{
            return 44;
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == 1 && self.customController.isEditing){
            return 1;
        }else{
            return super.tableView(tableView, numberOfRowsInSection: section);
        }
    }
    
    lazy var customController:DAnalysisDateCustomController = {
        var controller = DAnalysisDateCustomController();
        controller.doneClosure = {(beginDate, endDate) in
            let row = self.customSection.first!;
            self.setCustomDates(beginDate, end: endDate)
            row.detail = self.analysis.intervalValue.customDateString;
            self.tableView.reloadData();
        }
        return controller;
    }();
    
    var analysis:DAnalysisDatePreference;
    func setCustomDates(_ begin:Date, end:Date) -> Void{
        
        let subValue:DAnalysisDatePreference.IntervalValue = DAnalysisDatePreference.IntervalValue();
        subValue.subType = .Custom;
        subValue.customEndDate = end;
        subValue.customBeginDate = begin;
        subValue.latestSubValue = -1;
        
        var interval:DTableRowItem? = nil;
        var calendar:Calendar = Calendar.current;
        calendar.firstWeekday = 2;
        var string:String = "";
        switch self.analysis.intervalType {
        case .Day:
            interval = self.intervalSection[0];
            let comp = calendar.dateComponents([.day], from: begin, to: end);
            string = "\(comp.day! + 1)天(\(begin.defaultDateString()) - \(end.defaultDateString()))";
        case .Week:
            interval = self.intervalSection[1];
            let comp = calendar.dateComponents([.weekOfYear], from: begin, to: end);
            string = "\(comp.weekOfYear! + 1)周(\(begin.defaultDateString()) - \(end.defaultDateString()))";
        case .Month:
            interval = self.intervalSection[2];
            let dateFormatter = DateFormatter();
            dateFormatter.dateFormat = "yyyy-MM";
            let comp = calendar.dateComponents([.month], from: begin, to: end);
            string = "\(comp.month! + 1)月(\(dateFormatter.string(from: begin)) - \(dateFormatter.string(from: end)))";
        }
        subValue.customDateString = string;
        interval?.userInfo = subValue;
        self.analysis.intervalValue = subValue;
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.section == 0){
            let cell = super.tableView(tableView, cellForRowAt: indexPath);
            cell.accessoryType = (indexPath.row == self.analysis.intervalType.rawValue ? .checkmark : .none);
            return cell;
        }else if (indexPath.section == 1){
            if (self.customController.isEditing){
                var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "date");
                if (cell == nil){
                    cell = UITableViewCell(style: .default, reuseIdentifier: "date");
                    self.customController.configDatePickerCell(cell!);
                }
                return cell!;
            }else{
                let cell = super.tableView(tableView, cellForRowAt: indexPath);
                cell.accessoryType = (self.analysis.intervalValue.subType == .Latest && indexPath.row == self.analysis.intervalValue.latestSubValue! ? .checkmark : .none);
                return cell;
            }
        }else if indexPath.section == 2 {
            if (self.customController.isEditing){
                var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "custom");
                if (cell == nil){
                    cell = UITableViewCell(style: .default, reuseIdentifier: "custom");
                    self.customController.configCustomDateCell(cell!);
                }
                cell?.textLabel?.text = "自定义...";
                return cell!;
            }else{
                let cell = super.tableView(tableView, cellForRowAt: indexPath);
                cell.accessoryType = self.analysis.intervalValue.subType == .Custom ? .checkmark : .none;
                return cell;
            }
        }else{
            let cell = super.tableView(tableView, cellForRowAt: indexPath);
            cell.accessoryType = (self.analysis.intervalValue.subType == .All ? .checkmark : .none);
            return cell;
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (indexPath.section == 0){
            tableView.deselectRow(at: indexPath, animated: true);
            if (self.analysis.intervalType.rawValue != indexPath.row){
                self.selectInterval(indexPath);
            }
        }else if (indexPath.section == 1){
            tableView.deselectRow(at: indexPath, animated: true);
            if (self.analysis.intervalValue.subType != .Latest || self.analysis.intervalValue.latestSubValue != indexPath.row){
                self.selectLatest(indexPath);
            }
        }else if (indexPath.section == 2){
            self.selectCustomDate(indexPath);
        }else if (indexPath.section == 3){
            if (self.analysis.intervalValue.subType != .All){
                self.selectAll();
            }
            tableView.deselectRow(at: indexPath, animated: true);
        }
    }
    
    func reloadCustomController(){
        self.customController.intervalType = self.analysis.intervalType;
        if (self.analysis.intervalValue.customBeginDate != nil){
            self.customController.beginDate = self.analysis.intervalValue.customBeginDate!;
        }
        if (self.analysis.intervalValue.customEndDate != nil){
            self.customController.endDate = self.analysis.intervalValue.customEndDate!;
        }
    }
    
    func selectCustomDate(_ indexPath:IndexPath) {
        if (!self.customController.isEditing){
            self.customController.isEditing = true;
            self.reloadCustomController();
            self.tableView.reloadData();
            self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false);
        }else{
            tableView.deselectRow(at: indexPath, animated: true);
            self.customController.isEditing = false;
            self.tableView.reloadData();
        }
    }
    
    func selectAll() -> Void{
        let subValue:DAnalysisDatePreference.IntervalValue = DAnalysisDatePreference.IntervalValue();
        subValue.subType = .All;
        subValue.customEndDate = nil;
        subValue.customBeginDate = nil;
        subValue.latestSubValue = nil;
        self.analysis.intervalValue = subValue;
        self.tableView.reloadData();
    }

    func selectLatest(_ indexPath:IndexPath) -> Void{
        let subValue:DAnalysisDatePreference.IntervalValue = DAnalysisDatePreference.IntervalValue();
        subValue.subType = .Latest;
        subValue.customEndDate = nil;
        subValue.customBeginDate = nil;
        subValue.latestSubValue = indexPath.row;
        self.analysis.intervalValue = subValue;
        self.tableView.reloadData();
    }
    
    func selectInterval(_ indexPath:IndexPath) -> Void{//sectionItems
        self.analysis.intervalType = DAnalysisDatePreference.IntervalTypes(rawValue: indexPath.row)!;
        let interval = self.sectionItems[indexPath.section][indexPath.row];
        
        if (interval.userInfo != nil){
            self.analysis.intervalValue = interval.userInfo as! DAnalysisDatePreference.IntervalValue;
            self.customSection.first!.detail = self.analysis.intervalValue.customDateString;
        }else{
            self.analysis.intervalValue = DAnalysisDatePreference.IntervalValue();
            self.customSection.first!.detail = nil;
        }
        self.reloadCustomController();
        self.replaceSection1();
        self.tableView.reloadData();
    }
    
    func replaceSection1() -> Void{
        switch self.analysis.intervalType {
        case .Day:
            self.sectionItems.replaceSubrange(Range(uncheckedBounds:(1,2)), with: [self.daySection]);
        case .Week:
            self.sectionItems.replaceSubrange(Range(uncheckedBounds:(1,2)), with: [self.weekSection]);
        case .Month:
            self.sectionItems.replaceSubrange(Range(uncheckedBounds:(1,2)), with: [self.monthSection]);
        }
    }
}
